const express = require('express')
const app = express()
// 数据验证
const joi = require('joi')
// 配置cors跨域
const cors = require('cors')
// 注册为全局中间件
app.use(cors())

// 配置解析表单数据的中间件 内置中间件
app.use(express.urlencoded({
	extended: false
}))

// 在路由之前封装res.cc函数
app.use((req, res, next) => {
	// status 1表示失败
	// err可能是一个出错误对象 也可能是字符串
	res.cc = function(err, status = 1) {
		res.send({
			status,
			message: err instanceof Error ? err.message : err
		})
	}
	next()
})

// 路由之前配置解析Token的中间件
// 导入配置文件
const config = require('./config')
// 解析token的中间件
const expressJWT = require('express-jwt')
// 使用 .unless({path:[/^\/api\//]})来指定哪些接口不需要进行token认证
// algorithms:7.0以后的版本需要配置algorithms算法
app.use(expressJWT({
	secret: config.jwtSecretKey
}).unless({
	path: [/^\/api\//]
}))
// 导入并注册路由模块
const userRouter = require('./router/user')
app.use('/api', userRouter)

// app.get('/hahaha',function(req,res){
//     res.send('HellowWorld')
// });
// 用户信息
const userinfoRouter = require('./router/userinfo')
app.use('/my', userinfoRouter)
// 文章
const artCateRouter = require('./router/artcate')
app.use('/my/article', artCateRouter)


const plant = require('./router/plant')
app.use('/my/plant', plant)
// 信息验证,错误级别中间件
app.use((err, req, res, next) => {
	if (err instanceof joi.ValidationError) return res.cc(err)
	if (err.name === 'UnauthorizedError') return res.cc('身份认证失败！')
	res.cc(err)
})



app.listen(8888, () => {
	console.log('服务器启动成功！http://127.0.0.1:8888')
})

// 每分钟请求
const moment = require('moment')
// 邮箱
let nodemailer = require('nodemailer');
// let d = new Date(); `${d.getHours()}:${d.getHours()}`
let plantTime = moment().utcOffset(8).format('HH:mm')
let plantTimeDay = moment().utcOffset(8).format('YYYY-MM-DD')
const db = require('./db/index.js')
let minutePlain = setInterval(() => {
	console.log(plantTime)
	// 这边需要加一个看是否订阅
	plantTime = moment().utcOffset(8).format('HH:mm')
	plantTimeDay = moment().utcOffset(8).format('YYYY-MM-DD')
	// const sqlmail = 'select * from plant where plantStart=? and is_start=? and plantTime=?'
	const sqlmail = 'select * from plant where plantStart=? and is_start=?'
	const sqlmail2 = 'select * from plant where plantEnd=? and is_end=?'
	const bian = '任务开启提醒'
	const bian2 = '任务结束提醒'
	timeFa(sqlmail, plantTime, plantTimeDay, bian)
	timeFa(sqlmail2, plantTime, plantTimeDay, bian2)
}, 6000000)

function timeFa(sqlmail, plantTime, plantTimeDay, bian) {
	db.query(sqlmail, [plantTime, 'true'], function(err, results) {
		if (err) {
			return console.log('任务请求错误！')
		}
		if (results.length == 0) {
			return console.log('数据为空！')
		}
		let plantItems = JSON.stringify(results);
		plantItems = JSON.parse(plantItems)
		for (let i = 0; i < plantItems.length; i++) {
			const sqlplain = `select mail.mail
							  from mail inner join ev_users
							  on mail.mailId=ev_users.emailId where user_id=?;`
			db.query(sqlplain, plantItems[i].userId, (err, result) => {
				if (err) {
					return console.log(err)
				}
				let tixing = JSON.stringify(result);
				tixing = JSON.parse(tixing)
				// let resultt = JSON.parse(result);
				console.log(tixing[0].mail)
				let options = {
					from: `${bian}<3515722788@qq.com>`,
					to: `<${tixing[0].mail}>`,
					bcc: '密送',
					subject: `${plantItems[i].plantStart}-${plantItems[i].plantEnd}:${plantItems[i].plantTitle}`,
					text: `${plantItems[i].plantNotes}`,
					// html: `<h1>hello zhy ${randomNum}</h1>`
				};
				console.log(options)
				let transporter = nodemailer.createTransport({
					host: 'smtp.qq.com',
					port: 587,
					secure: false,
					auth: {
						user: '3515722788@qq.com',
						pass: 'olowkvmoqhwhchbh'
					}
				})
				transporter.sendMail(options, function(err, msg) {
					if (err) {
						console.log(err);
					} else {
						console.log('提醒成功' + plantItems[0])
					}
				})
			})
		}

	})
}
